package com.book.bookshop.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.book.bookshop.entity.Book;
import com.book.bookshop.mapper.BookMapper;
import com.book.bookshop.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
/**
 * 图书控制器
 */
@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;

    @Autowired
    private BookMapper bookMapper;


    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    /**
     * 获取图书信息
     */
    @RequestMapping("/getBookData")
    public String getBookData(Model model,Integer page,Integer category){
        //mybatis plus分页
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category",category);
        IPage<Book> iPage = bookService.page(new Page<>(page,4),queryWrapper);
        model.addAttribute("bookList",iPage.getRecords());
        model.addAttribute("pre",iPage.getCurrent() - 1);
        model.addAttribute("next",iPage.getCurrent() + 1);
        model.addAttribute("cur",iPage.getCurrent());
        model.addAttribute("last",iPage.getPages());
        model.addAttribute("category",category);
        return "bookData";
    }

    /**
     * 图书列表页
     */
    @RequestMapping("/bookList")
    public String bookList(String category, Model model){
        model.addAttribute("category",category);
        return "books_list";
    }

    /**
     * 拉取全部图书
     * @param model
     * @return
     */

    @RequestMapping("/bookList1")
    public String bookList(Model model){
        Book book = new Book();
        List<Book> books = book.selectAll();
        model.addAttribute("bookList1",books);
        return "allBookDate";
    }

    /**
     * 获取图书列表数据
     */
    @RequestMapping("/getBookListData")
    public String getBookListData(String category,Integer page, Integer pageSize, Model model){
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category",category);
        IPage<Book> iPage = bookService.page(new Page<Book>(page,pageSize),queryWrapper);
        model.addAttribute("bookList",iPage.getRecords());
        model.addAttribute("pre",iPage.getCurrent() - 1);
        model.addAttribute("next",iPage.getCurrent() + 1);
        model.addAttribute("cur",iPage.getCurrent());
        model.addAttribute("pages",iPage.getPages());
        model.addAttribute("category",category);
        model.addAttribute("pageSize",pageSize);
        return "booksListData";
    }


    /**
     * 图书详情
     */
    @RequestMapping("/detail")
    public String detail(Integer id,Model model){
        Book book = bookService.getById(id);
        model.addAttribute("book",book);
        return "details";

    }
    /**
     * 更新
     */
    @ResponseBody
    @RequestMapping("/update")
    public String update(Book book){
        bookService.updateById(book);
        return "success";
    }
    /**
     * 添加
     *
     */
    @PostMapping("/save")
    @ResponseBody
    public ModelAndView saveBook(Book book,MultipartFile img){
        ModelAndView mv = new ModelAndView();
        String path = "D:\\workplace\\book-shop\\src\\main\\resources\\static\\images\\"; // 保存路径
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String suffix = Objects.requireNonNull(img.getOriginalFilename()).substring(img.getOriginalFilename().lastIndexOf("."));
        if (!suffix.equals(".jpg")) {
            System.out.println("上传失败！");
        }
        try {
            // Spring提供了文件操作类FileCopyUtils
            FileCopyUtils.copy(img.getInputStream(), new FileOutputStream(path + fileName + suffix));
            System.out.println(book.toString());
            book.setImgUrl(fileName+suffix);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("上传失败！");

        }

         bookService.save(book);
         mv.setViewName("redirect:/book/index");
        return mv;
    }

    /**
     *
     * 删除
     */
    @ResponseBody
    @RequestMapping("/delete")
    public String delete(Integer bookId){
        bookService.removeById(bookId);
        return "success";
    }


    /**
     *
     * @查询
     * @return
     */
    @ResponseBody
    @RequestMapping("/select")
    public String select(String name){
            QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
            QueryWrapper<Book> name1 = queryWrapper.like("name", name);
            try {
                if (name1 != null){
                    Book one = bookService.getOne(name1);
                    String id = String.valueOf(one.getId());
                    return id;
                }else{
                    return null;
                }
            }catch (java.lang.NullPointerException e){
                return null;
            }
    }

}